package cRedis

import (
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"
)

type GoRedisConnector struct {
	connection string
	config     *RedisConf_Client
	client     *redis.Client
}

func (i *GoRedisConnector) GetConnection() string {
	return i.connection
}

func (i *GoRedisConnector) GetClient() *redis.Client {
	return i.client
}

func (i *GoRedisConnector) Connect() error {
	if i.config == nil {
		return fmt.Errorf("redis client config is nil")
	}

	addr := fmt.Sprintf("%s:%d", i.config.Host, i.config.Port)
	pool := &RedisConf_Client_Pool{}

	if i.config.Pool != nil {
		pool = i.config.Pool
	}

	if pool.MinIdleConns <= 0 {
		pool.MinIdleConns = 1
	}

	if pool.IdleTimeout <= 0 {
		pool.IdleTimeout = 10
	}

	if pool.Size <= 0 {
		pool.Size = 10
	}

	option := &redis.Options{
		Addr:         addr,
		Password:     i.config.Auth,
		DB:           int(i.config.DB),
		MaxRetries:   int(i.config.Retries),
		DialTimeout:  time.Duration(i.config.DialTimeout) * time.Second,
		ReadTimeout:  time.Duration(i.config.DialTimeout) * time.Second,
		WriteTimeout: time.Duration(i.config.DialTimeout) * time.Second,
		PoolSize:     int(pool.Size),
		MinIdleConns: int(pool.MinIdleConns),
		PoolTimeout:  time.Duration(pool.PoolTimeout) * time.Second,
		IdleTimeout:  time.Duration(pool.IdleTimeout) * time.Second,
	}

	i.client = redis.NewClient(option)

	return nil
}

func NewGoRedisConnector(connection string, config *RedisConf_Client) *GoRedisConnector {
	return &GoRedisConnector{
		connection: connection,
		config:     config,
		client:     nil,
	}
}
